package com.example.fileserver_API.Interfaces.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.fileserver_API.Dao.UploadpicturesMappers;
import com.example.fileserver_API.Entity.PO.uploadpictures;
import com.example.fileserver_API.Entity.VO.APIResult;
import com.example.fileserver_API.FixedValue.SetSettings;
import com.example.fileserver_API.Interfaces.IService.IGetFileService;
import com.example.fileserver_API.utils.APIResultUtils;
import com.example.fileserver_API.utils.RedisUtils;
import com.example.fileserver_API.utils.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

@Service
public class GetFileService implements IGetFileService {
    @Resource
    UploadpicturesMappers _uploadpicturesMappers;
    @Resource
    RedisUtils redisUtils;


    /**
     * 获取图片上传信息
     *
     * @param guid 图片记录表的唯一标识符
     * @return uploadpictures
     */
    @Override
    public uploadpictures GetImg(String guid) throws Exception {
        if (StringUtils.isBlank(guid))
            throw new Exception("未获取到文件的标识符");
        // 读取图片的地址
        uploadpictures uploadpictures = _uploadpicturesMappers.selectById(guid);
        if (uploadpictures == null)
            throw new Exception("未获取到文件记录信息");
        return uploadpictures;
    }

    /**
     * 删除某个文件
     *
     * @param guid 文件guid
     * @return APIResult
     */
    @Override
    public APIResult DeleteFile(String guid) {
        System.out.println("删除文件唯一标识符" + guid);
        String path = redisUtils.GetHashValue(SetSettings.sys_syssetting, SetSettings.sys_path).toString();
        if (StringUtils.isBlank(path))
            return APIResultUtils.error("未查询到配置的[path]地址配置！");
        QueryWrapper<uploadpictures> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("guid", guid);
        String pic = _uploadpicturesMappers.selectOne(queryWrapper).getFilepath();
        if (StringUtils.isBlank(pic))
            return APIResultUtils.error("未查询到该文件的地址，请刷新重试！");
        String picpath = path + pic;// 文件路径
        System.out.println("文件地址：" + picpath);
        File file = new File(picpath);
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("文件已成功删除");
                _uploadpicturesMappers.delete(queryWrapper);
                return APIResultUtils.success("文件已成功删除", "文件已成功删除！");
            } else {
                System.out.println("无法删除文件。");
                return APIResultUtils.error("无法删除文件。");
            }
        } else {
            System.out.println("文件不存在。");
            return APIResultUtils.error("文件不存在。");
        }
    }

    /**
     * 获取视频（不分片)
     * @param guid 图片guid
     * @return APIResult
     */
    @Override
    public ResponseEntity<org.springframework.core.io.Resource> GetVideo(String guid) {
        try {
            String path = redisUtils.GetHashValue(SetSettings.sys_syssetting, SetSettings.sys_path).toString();
            if (StringUtils.isBlank(path)) {
                throw new Exception("未查询到配置的[path]地址配置！");
            }

            QueryWrapper<uploadpictures> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("guid", guid);
            uploadpictures info = _uploadpicturesMappers.selectOne(queryWrapper);

            if (info == null) {
                return ResponseEntity.notFound().build();
            }

            Path filePath = Paths.get(path + info.getFilepath());
            File videoFile = filePath.toFile();

            if (!videoFile.exists() || !videoFile.isFile()) {
                return ResponseEntity.notFound().build();
            }

            // 设置Content-Type为video/mp4
            MediaType mediaType = MediaType.parseMediaType("video/mp4");

            FileSystemResource resource = new FileSystemResource(videoFile);

            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .body(resource);
        } catch (Exception e) {
            // 处理异常逻辑
            e.printStackTrace(); // 可以记录异常以便调试
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
}
